package soar.template.springboot.service.hello.controller;

import java.io.BufferedReader;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

public class BaseController implements ApplicationContextAware
{
    private final static Logger logger = LoggerFactory
            .getLogger(BaseController.class);

    protected ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        this.context = context;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public String index()
    {
        return String.format("你好！ local @ %s", DateTimeFormatter
                .ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }

    protected SortedMap<String, String> get_request_params(
            HttpServletRequest request)
    {
        try
        {
            SortedMap<String, String> params = new TreeMap<>();

            Enumeration<String> en = request.getParameterNames();
            while (en.hasMoreElements())
            {
                String key = ((String) en.nextElement()).trim();
                String val = Optional.ofNullable(request.getParameter(key))
                        .map(String::trim).orElse("");
                if (!val.isEmpty())
                {
//                    params.put(key, URLDecoder.decode(val, "UTF-8"));
                    params.put(key, val);
                }
            }

            return params;
        }
        catch (Exception e)
        {
            logger.error("wrapped reasponse error: {}", e);
            return new TreeMap<>();
        }
    }

    protected String get_request_body(HttpServletRequest servletRequest)
    {
        try
        {
            BufferedReader br = servletRequest.getReader();
            StringBuilder sbld = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
            {
                sbld.append(line);
            }
            return sbld.toString().trim();
        }
        catch (Exception e)
        {
            logger.error("wrapped reasponse error: {}", e);
            return "";
        }
    }
}
